package com.cm.etax.tianjin;

import com.cm.etax.BaseEtax;
import com.cm.etax.BaseFunction;
import com.cm.etax.EtaxConfig;
import com.cm.etax.FunctionResult;
import com.cm.etax.exceptions.EtaxException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

import java.util.Objects;

/**
 * 主菜单管理方法
 *
 * @author LWang 2023.01.29
 * @since 1.0.0
 */
@Slf4j
public class MenuFunction extends BaseFunction {
    public MenuFunction(BaseEtax etax) {
        super(etax);
    }

    /**
     * 切换电子税务局主页菜单
     *
     * @param type 功能类型
     * @param menu 功能名称
     * @return 切换结果
     */
    public FunctionResult<Object> choiceMainMenu(String type, String menu) {
        // 1. 返回电子税务局首页
        rpa().visit(config().getMainUrl());
        try {
            // 判断是否存在 divAlertBox 对话框，内容为
            rpa().findElementWithInnerText("用户未登录！", By.cssSelector("#divAlertBox span"), WAIT_TIME / 2);
            return new FunctionResult<>(false, "切换菜单失败，用户未登录！", null);
        } catch (NoSuchElementException ignore) {
            // 继续执行
        }
        // 切换菜单类型
        try {
            var typeTab = rpa().findElementWithInnerText(type, By.cssSelector("div.main-rightPane-topPane li[role=\"presentation\"] a[role=\"tab\"]"), WAIT_TIME);
            rpa().click(typeTab);
            if (config().getLoginType() == EtaxConfig.LOGIN_TYPE_ENTERPRISE) {
                // 切换到菜单 iFrame
                var typeId = typeTab.getAttribute("aria-controls");
                rpa().switchToFrame(By.cssSelector("div#" + typeId + " iframe"), WAIT_TIME);
            }
            try {
                rpa().click(rpa().findElementWithInnerText(menu, By.cssSelector("li.menuContainerLi span.menuContainerLi-span"), WAIT_TIME / 2));
            } catch (Exception e) {
                rpa().click(rpa().findElementWithInnerText(menu, By.cssSelector("li.menuContainerLi-file span.menuContainerLi-span"), WAIT_TIME / 2));
            }
            return new FunctionResult<>(true, "菜单切换成功。", null);
        } catch (Exception e) {
            return handleException(e, "菜单切换失败，");
        } finally {
            rpa().switchToParent();
        }
    }

    /**
     * 切换账户中心菜单
     *
     * @param first  一级菜单
     * @param second 二级菜单
     * @return 切换结果
     */
    public FunctionResult<Object> choiceAccountCenterMenu(String first, String second) {
        try {
            var header = rpa().findElement(By.cssSelector(".content .sidebar-container .sidebar-head"));
            var headerText = "账户中心";
            if (!rpa().textEquals(header, headerText)) {
                return new FunctionResult<>(false, "切换账户中心菜单失败，请先进入该功能！", null);
            }
        } catch (NoSuchElementException e) {
            return new FunctionResult<>(false, "切换账户中心菜单失败，" + e.getMessage(), null);
        }
        try {
            // 切换一级菜单
            rpa().findElementWithInnerText(first, By.cssSelector("li.el-submenu span"), WAIT_TIME).click();
            // 切换二级菜单
            rpa().findElement(By.cssSelector("li.el-menu-item[title=\"" + second + "\"]"), WAIT_TIME).click();
            return new FunctionResult<>(true, "切换账户中心菜单成功。", null);
        } catch (Exception e) {
            return handleException(e, "切换账户中心菜单失败，");
        }
    }

    /**
     * 菜单标志：点 - 功能菜单
     */
    private static final String MENU_DOT = "•";

    /**
     * 选择目录菜单
     *
     * @param menu       菜单内容
     * @param needFolder true：目录菜单；false：文件菜单
     * @return 菜单元素
     */
    private WebElement choiceMenu(String menu, boolean needFolder) {
        var menuElements = rpa().findElements(By.cssSelector(".leftPanel-li-div"), WAIT_TIME);
        for (var menuElement : menuElements) {
            var point = menuElement.findElement(By.cssSelector("span.leftPane-pointer"));
            var isFile = rpa().textEquals(point, MENU_DOT);
            if (needFolder ^ isFile) {
                var spans = menuElement.findElements(By.tagName("span"));
                for (var span : spans) {
                    if (rpa().textEquals(span, menu)) {
                        return span;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 进入功能菜单
     *
     * @param menus 菜单顺序
     * @return 执行结果
     */
    public FunctionResult<Object> choiceFunctionMenu(String... menus) {
        if (Objects.isNull(menus) || menus.length == 0) {
            return new FunctionResult<>(false, "功能菜单选择失败，未指定要进入的功能", null);
        }
        try {
            for (var i = 0; i < menus.length; i++) {
                WebElement menu;
                if (i == menus.length - 1) {
                    menu = choiceMenu(menus[i], false);
                } else {
                    menu = choiceMenu(menus[i], true);
                }
                if (Objects.isNull(menu)) {
                    throw new EtaxException(menus[i] + "不存在！");
                } else {
                    menu.click();
                }
            }

            // 身份识别判断
            var functionObj = etax().function(IdentityAuthenticationFunction.class);
            if (functionObj.needIdentityAuthentication()) {
                var result = etax().function(IdentityAuthenticationFunction.class).identityAuthentication();
                if (result.success()) {
                    return choiceFunctionMenu(menus);
                } else {
                    throw new EtaxException(result.message());
                }
            }
            // 是否可以使用判断
            try {
                var dialog = rpa().findElement(By.id("divAlertBox"), WAIT_TIME);
                if (!Objects.isNull(dialog)) {
                    throw new EtaxException(StringUtils.trim(dialog.getText()));
                }
            } catch (Exception ignore) {
            }
            return new FunctionResult<>(true, "切换功能菜单成功。", null);
        } catch (Exception e) {
            return handleException(e, "切换功能菜单失败，");
        }
    }
}
